/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestors;

import com.gr.uth.dao.UserDAO;
import com.gr.uth.dao.controllers.UserDAOJpaController;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 *
 * @author mruiz
 */
public class LoginService {

    private static final String PERSISTENCE_UNIT_NAME = "startupme";
    private static EntityManagerFactory factory;

    public static UserDAO login(String email, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        UserDAO result;
        if (email != null && password != null) {
            factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            UserDAOJpaController uc = new UserDAOJpaController(null, factory);
            try {
                result = uc.findUserDAOByEmail(email);
            } catch (NoResultException e) {
                return null;
            }
            System.out.println("User FOUND: " + result);
            if (result != null) {
                if (result.getPass().equals(encodeInMD5(password))) {
                    return result;
                }
            }
        }
        return null;
    }

    private static String encodeInMD5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {

        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(password.getBytes("UTF8"));
        byte s[] = m.digest();
        String result = "";
        for (int i = 0; i < s.length; i++) {
            result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
        }
        return result;
    }
}
